package admin.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/AdminExpress/index.html")
public class AdminFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 此过滤器作用，当用户未登录时，不可访问主页index.html
     * @param servletRequest  发出的页面请求
     * @param servletResponse 去响应的页面
     * @param filterChain  过滤器对象
     * @throws IOException  IO异常
     * @throws ServletException  网页异常
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //取存储的session值
        String userName = (String) request.getSession().getAttribute("userName");

        //System.out.println(userName);

        if (userName !=null){
            //请求通过此过滤器，给其放行
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            //条件不满足时，重定向页面到登录页面
            response.sendRedirect("/AdminExpress/login.html");

        }
    }

    @Override
    public void destroy() {

    }
}
